# coding=utf-8
from flask import current_app
from flask import g
from flask import redirect
from flask import render_template, jsonify
from flask import request

from info import constants
from info import db
from info.models import User, Category, News
from info.utils.commom import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import profiles_blue

# 获取我的关注
# 请求路径: /user/user_follow
# 请求方式: GET
# 请求参数:page
# 返回值: 渲染user_follow.html页面,字典data数据
@profiles_blue.route('/user_follow')
@user_login_data
def user_follow():
    #1, 获取参数page
    page = request.args.get("page","1")

    #2, 参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    #3, 获取关注的用户
    try:
        paginate = g.user.followed.paginate(page,2,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")

    #4,数据拼接
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    author_list = []
    for author in items:
        author_list.append(author.to_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "author_list":author_list
    }

    #5, 返回响应
    return render_template('news/user_follow.html',data=data)

#获取用户发布的新闻
# 请求路径: /user/news_list
# 请求方式:GET
# 请求参数:page
# 返回值:GET渲染user_news_list.html页面
@profiles_blue.route('/news_list')
@user_login_data
def news_list():
    #1, 获取参数page
    page = request.args.get("page","1")

    #2, 参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    #3, 获取用户发布新闻
    try:
        paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page,2,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    #4,数据拼接
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }

    #5, 返回响应
    return render_template('news/user_news_list.html',data=data)

# 获取/设置,新闻发布
# 请求路径: /user/news_release
# 请求方式:GET,POST
# 请求参数:GET无, POST ,title, category_id,digest,index_image,content
# 返回值:GET请求,user_news_release.html, data分类列表字段数据, POST,errno,errmsg
# 走不到post方法
@profiles_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    #1,判断请求方式,如果是get携带分类数据渲染页面
    if request.method == "GET":

        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_list = []
        for category in categories:
            category_list.append(category.to_dict())

        return render_template('news/user_news_release.html',categories=category_list)

    #2,如果是post
    #2.1 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    #2.2 校验参数
    #为空校验
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #图片上传
    try:
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)

    #2.3 数据入库
    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1 #1表示审核中

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻发布失败")

    #2.4 返回响应
    return jsonify(errno=RET.OK,errmsg="success")

#获取用户收藏的新闻
#请求方式: GET
#请求路径: /user/collection
#请求参数: page
#返回响应: user_collection.html, 携带新闻数据
@profiles_blue.route('/collection')
@user_login_data
def collection():
    #1, 获取参数page,前端分析，page什么情况之下可以获取？
    page = request.args.get("page","1")

    #2, 参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    #3, 获取新闻
    try:
        paginate = g.user.collection_news.paginate(page, 2, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    #4,数据拼接
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }

    #5, 返回响应
    return render_template('news/user_collection.html',data=data)

# 获取/设置用户密码
# 请求路径: /user/pass_info
# 请求方式:GET,POST
# 请求参数:GET无, POST有参数,old_password, new_password
# 返回值:GET请求: user_pass_info.html页面, POST请求: errno, errmsg
@profiles_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    #1,  判断请求方式,如果是GET渲染页面
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    #2,如果是POST请求
    #2.1 获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    new_password2 = request.json.get("new_password2")

    # 2.2 校验参数
    # 2.2.1 为空检验
    if not all([old_password,new_password,new_password2]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    # 2.2.2 两次新密码是否一致
    if new_password2 != new_password:
        return jsonify(errno=RET.DATAERR,errmsg="两次密码不一致")

    #2.2.3 判断旧密码是否正确
    if not g.user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR,errmsg="原密码错误")

    #2.3 数据入库
    g.user.password = new_password

    #2.4 返回响应
    return jsonify(errno=RET.OK,errmsg="修改成功")


# 获取/设置,用户头像上传
# 请求路径: /user/pic_info
# 请求方式:GET,POST
# 请求参数:无, POST有参数,avatar
# 返回值:GET请求: user_pci_info.html页面,data字典数据, POST请求: errno, errmsg,avatar_url
@profiles_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    #1,判断请求方式,如果是GET渲染页面携带用户头像
    if request.method == "GET":
        data = {
            "user_info": g.user.to_dict(),
        }
        return render_template('news/user_pic_info.html',data=data)

    #2,如果是POST请求
    #2.1 获取参数 submitajax请求方式
    # avatar = request.form.get("avatar")
    avatar = request.files.get("avatar")

    #2.2 校验参数
    if not avatar:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #2.3 上传头像,数据入库
    try:
        image_name = image_storage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="七牛云异常")

    if not image_name:
        return jsonify(errno=RET.NODATA,errmsg="图片上传失败")

    g.user.avatar_url = image_name

    #2.4 返回响应
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    return jsonify(errno=RET.OK,errmsg="上传成功",data={"avatar_url":avatar_url})


# 请求路径: /user/base_info
# 请求方式:GET,POST
# 请求参数:POST请求有参数,nick_name,signature,gender
# 返回值:errno,errmsg
@profiles_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():

    if request.method == "GET":
        data = {
            "user_info": g.user.to_dict() if g.user else "",
        }
        return render_template("news/user_base_info.html", data=data)

    signature = request.json.get("signature", None)
    nick_name = request.json.get("nick_name", None)
    gender = request.json.get("gender", None)

    if not all([signature,nick_name,gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 数据入库
    g.user.signature = signature
    g.user.nick_name = nick_name
    g.user.gender = gender

    return jsonify(errno=RET.OK, errmsg="修改信息成功")


@profiles_blue.route('/info')
@user_login_data
def info():
    if not g.user:
        return redirect("/")

    data = {
        "user_info":g.user.to_dict() if g.user else "",
    }
    return render_template("news/user.html", data=data)